package com.yufeng.learning.client.ribbon;

import com.yufeng.learning.client.config.GreetingRibbonConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@RestController
//Ribbon client, 名字可以与外部服务不一致
@RibbonClient(name="greetingService", configuration = GreetingRibbonConfiguration.class)
public class RibbonApplication {
    //启用Load Balance support
    @LoadBalanced
    @Bean
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
    @Autowired
    private RestTemplate restTemplate;

	public static void main(String[] args) {
	    SpringApplication.run(RibbonApplication.class, args);
	}

	@RequestMapping("/sayHello")
	public String sayHello (@RequestParam(value = "name", defaultValue = "路人甲")String name) {
	    //greetingService 配置在yml文件中, 外部服务定义
	    String greetingWord = this.restTemplate.getForObject("http://greetingService/greetingWord", String.class);
        return String.format("%s : %s", greetingWord, name);
    }
}
